<template>
  <div class="internet-account-analysis-page">
    <!-- 页面标题与操作区 -->
    <div class="page-header">
      <el-page-header content="互联网账号相似性分析" @back="handleGoBack" />
      <div class="header-actions">
        <!-- 分析阈值设置 -->
        <el-form :inline="true" :model="analysisForm" class="threshold-form">
          <el-form-item label="粉丝重叠阈值" prop="overlapThreshold">
            <el-input-number
              v-model="analysisForm.overlapThreshold"
              :min="10"
              :max="100"
              :step="5"
              suffix-icon="el-icon-percentage"
              placeholder="设置相似判定阈值"
              @change="handleThresholdChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleStartAnalysis"
              :loading="analysisLoading"
              :disabled="!selectedAccount"
            >
              开始相似账号分析
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 核心内容区：账号列表 + 相似分析结果 -->
    <el-row :gutter="20" class="content-container">
      <!-- 左侧：互联网账号列表 -->
      <el-col :span="10">
        <el-card shadow="hover" class="account-list-card">
          <template #header>
            <div class="card-header">
              <span>互联网账号列表</span>
              <!-- 账号筛选 -->
              <el-input
                v-model="searchForm.username"
                placeholder="搜索账号名（如@idrisla56079731）"
                prefix-icon="el-icon-search"
                class="search-input"
                @change="handleAccountSearch"
                @clear="handleAccountSearch"
                clearable
              />
            </div>
          </template>

          <!-- 账号表格 -->
          <el-table
            v-loading="accountListLoading"
            :data="accountList"
            row-key="id"
            border
            @row-click="handleSelectAccount"
            :highlight-current-row="true"
            :current-row-key="selectedAccount?.id"
          >
<!--            <el-table-column label="序号" type="index" width="60" align="center" />-->
            <el-table-column label="账号名" prop="username" align="center" min-width="180">
              <template #default="scope">
                <span class="username-tag">{{ scope.row.username }}</span>
              </template>
            </el-table-column>
            <el-table-column label="昵称" prop="nickname" align="center" min-width="120" />
            <el-table-column label="操作" align="center" width="120">
              <template #default="scope">
                <el-button
                  type="text"
                  icon="el-icon-user-check"
                  @click.stop="handleViewSimilar(scope.row)"
                  size="small"
                >
                  查相似
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="账号类型" prop="accountTypeName" align="center" min-width="120" />
            <el-table-column label="粉丝数" prop="fanCount" align="center" width="100">
              <template #default="scope">
                <span class="fan-count">{{ scope.row.fanCount || 0 }}</span>
              </template>
            </el-table-column>
<!--            <el-table-column label="采集时间" prop="collectTime" align="center" width="180">-->
<!--              <template #default="scope">-->
<!--                <el-date-picker-->
<!--                  v-model="scope.row.collectTime"-->
<!--                  type="datetime"-->
<!--                  format="YYYY-MM-DD HH:mm"-->
<!--                  value-format="X"-->
<!--                  disabled-->
<!--                  placeholder="无数据"-->
<!--                />-->
<!--              </template>-->
<!--            </el-table-column>-->
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-if="accountPage.total > 0"
            :current-page="accountPage.current"
            :page-size="accountPage.size"
            :total="accountPage.total"
            layout="prev, pager, next, jumper, ->, total"
            @current-change="handleAccountPageChange"
            class="account-pagination"
            background
          />
        </el-card>
      </el-col>

      <!-- 右侧：相似账号分析结果 -->
      <el-col :span="14">
        <el-card shadow="hover" class="analysis-result-card">
          <template #header>
            <div class="card-header">
              <span>相似账号分析结果</span>
              <!-- 分析状态标签 -->
              <div class="status-tag-group">
                <el-tag v-if="!selectedAccount" type="info" size="small">
                  请从左侧选择待分析账号
                </el-tag>
                <el-tag v-else-if="analysisLoading" type="warning" size="small">
                  <i class="el-icon-loading el-icon--right"></i>分析中...
                </el-tag>
                <el-tag v-else-if="hasAnalysisResult" type="success" size="small">
                  分析完成（阈值：{{ analysisForm.overlapThreshold }}%）
                </el-tag>
                <el-tag v-else type="danger" size="small">
                  未找到相似账号（可降低阈值重试）
                </el-tag>
                <!-- 目标账号信息：仅分析后显示 -->
                <el-tag
                  v-if="selectedAccount && (analysisLoading || hasAnalysisResult)"
                  type="primary"
                  size="small"
                  class="target-account-tag"
                >
                  目标账号：{{ selectedAccount.username }}
                </el-tag>
              </div>
            </div>
          </template>

          <!-- 无选中账号时 -->
          <div v-if="!selectedAccount" class="empty-result">
            <el-empty description="请从左侧列表选择一个账号进行分析" />
          </div>

          <!-- 分析加载中 -->
          <div v-else-if="analysisLoading" class="loading-result">
            <el-loading :text="`正在分析 ${selectedAccount.username} 的相似账号...`" fullscreen />
          </div>

          <!-- 分析结果展示（仅表格+统计） -->
          <div v-else class="result-content">
            <!-- 无相似账号时 -->
            <div v-if="!hasAnalysisResult" class="empty-result">
              <el-empty description="未找到符合阈值的相似账号" />
              <el-button
                type="text"
                @click="handleLowerThreshold"
                class="lower-threshold-btn"
              >
                点击降低阈值（当前：{{ analysisForm.overlapThreshold }}%）
              </el-button>
            </div>

            <!-- 有相似账号时 -->
            <div v-else class="table-container">
              <!-- 分析结果统计卡片 -->
              <div class="analysis-statistics">
                <el-descriptions title="分析概览" :column="3" border>
                  <el-descriptions-item label="目标账号">{{ selectedAccount.username }}</el-descriptions-item>
                  <el-descriptions-item label="目标账号粉丝数">{{ selectedAccount.fanCount || 0 }}</el-descriptions-item>
                  <el-descriptions-item label="相似账号数量">{{ similarAccountList.length }} 个</el-descriptions-item>
                  <el-descriptions-item label="判定阈值">{{ analysisForm.overlapThreshold }}%</el-descriptions-item>
                  <el-descriptions-item label="最高重叠率">{{ getMaxOverlapRate() }}%</el-descriptions-item>
                  <el-descriptions-item label="分析时间">{{ formatAnalysisTime() }}</el-descriptions-item>
                </el-descriptions>
              </div>

              <!-- 相似账号表格 -->
              <el-table
                :data="similarAccountList"
                row-key="id"
                border
                stripe
                v-loading="tableLoading"
                loading-text="加载相似账号数据..."
                class="similar-table"
                :default-sort="{ prop: 'overlapRate', order: 'descending' }"
              >
                <el-table-column label="排序" type="index" width="60" align="center" />
                <el-table-column label="账号名" prop="username" align="center" min-width="180">
                  <template #default="scope">
                    <span class="username-tag">{{ scope.row.username }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="昵称" prop="nickname" align="center" min-width="120" />
                <el-table-column label="账号类型" prop="accountTypeName" align="center" min-width="120" />
                <el-table-column label="粉丝数" prop="fanCount" align="center" width="100">
                  <template #default="scope">
                    <span>{{ scope.row.fanCount || 0 }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="共同粉丝数" prop="commonFanCount" align="center" width="120">
                  <template #default="scope">
                    <span class="common-fan-count">{{ scope.row.commonFanCount || 0 }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="粉丝重叠率" prop="overlapRate" align="center" width="160" sortable>
                  <template #default="scope">
                    <div class="overlap-rate-container">
                      <span class="rate-text">{{ scope.row.overlapRate }}%</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="120">
                  <template #default="scope">
                    <el-button
                      type="text"
                      icon="el-icon-eye"
                      @click="handleViewAccountDetail(scope.row.id)"
                      size="small"
                    >
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'

import {ElDescriptions, ElDescriptionsItem, ElEmpty, ElLoading, ElMessage} from 'element-plus'
// 引入API
import {InternetAccountApi, SimilarAccountApi} from '@/api/member/internetaccount/'

defineOptions({ name: 'SimilarAccountAnalysis' })

// 路由实例
const router = useRouter()

// 1. 账号列表相关状态
const accountListLoading = ref(false)
const accountList = ref<Array<{
  id: number
  username: string
  nickname: string
  accountTypeName: string
  fanCount: number
  collectTime: number | null
}>>([])
const accountPage = reactive({
  current: 1,
  size: 10,
  total: 0
})
const searchForm = reactive({
  username: '' // 账号名搜索
})

// 2. 相似分析相关状态
const analysisLoading = ref(false)
const tableLoading = ref(false)
const hasAnalysisResult = ref(false)
const analysisForm = reactive({
  overlapThreshold: 50 // 粉丝重叠阈值默认50%
})
const selectedAccount = ref<{
  id: number
  accountTypeId: number
  username: string
  nickname: string
  fanCount: number
} | null>(null) // 当前选中的分析账号
const similarAccountList = ref<Array<{
  id: number
  username: string
  nickname: string
  accountTypeName: string
  fanCount: number
  commonFanCount: number
  overlapRate: number
}>>([]) // 相似账号列表
const analysisTime = ref<number | null>(null) // 分析完成时间戳

// 页面挂载时加载账号列表
onMounted(() => {
  fetchAccountList()
})

// 3. 账号列表方法
// 获取账号列表
const fetchAccountList = async () => {
  accountListLoading.value = true
  try {
    const res = await InternetAccountApi.getInternetAccountPage({
      pageNum: accountPage.current,
      pageSize: accountPage.size,
      username: searchForm.username
    })
    accountList.value = res.list || []
    accountPage.total = res.total || 0
    // 若之前选中的账号不在列表中，清空选中状态
    if (selectedAccount.value && !accountList.value.some(item => item.id === selectedAccount.value?.id)) {
      selectedAccount.value = null
      hasAnalysisResult.value = false
    }
  } catch (err: any) {
    ElMessage.error('获取账号列表异常：' + (err.message || '请重试'))
  } finally {
    accountListLoading.value = false
  }
}

// 账号搜索
const handleAccountSearch = () => {
  accountPage.current = 1 // 重置页码
  fetchAccountList()
}

// 分页切换
const handleAccountPageChange = (page: number) => {
  accountPage.current = page
  fetchAccountList()
}

// 选中账号（行点击）
const handleSelectAccount = (row: any) => {
  selectedAccount.value = {
    id: row.id,
    accountTypeId: row.accountTypeId,
    username: row.username,
    nickname: row.nickname,
    fanCount: row.fanCount
  }
  // 选中新账号后，清空之前的分析结果
  hasAnalysisResult.value = false
  similarAccountList.value = []
}

// 查看单个账号的相似账号（快捷操作）
const handleViewSimilar = async (row: any) => {
  handleSelectAccount(row)
  // 自动触发分析
  handleStartAnalysis()
}

// 4. 相似分析核心方法
// 开始相似账号分析
const handleStartAnalysis = async () => {
  if (!selectedAccount.value) {
    ElMessage.warning('请先从左侧列表选择一个账号')
    return
  }

  if(selectedAccount.value.accountTypeId === 9
    || selectedAccount.value.accountTypeId === 10) {
    ElMessage.warning('只能选互联网账号！')
    return
  }

  analysisLoading.value = true
  tableLoading.value = true
  try {
    // 调用相似分析API
    const res = await SimilarAccountApi.analyzeSimilarAccounts({
      accountId: selectedAccount.value.id,
      overlapThreshold: analysisForm.overlapThreshold
    })
    similarAccountList.value = res.similarAccounts || []
    hasAnalysisResult.value = similarAccountList.value.length > 0
    analysisTime.value = Date.now() // 记录分析时间
    if (hasAnalysisResult.value) {
      ElMessage.success(`找到 ${similarAccountList.value.length} 个相似账号`)
    }
  } catch (err: any) {
    // ElMessage.error('分析请求异常：' + (err.message || '网络连接失败'))
    hasAnalysisResult.value = false
  } finally {
    analysisLoading.value = false
    tableLoading.value = false
  }
}

// 降低阈值快捷操作
const handleLowerThreshold = () => {
  analysisForm.overlapThreshold = Math.max(10, analysisForm.overlapThreshold - 10)
  handleStartAnalysis()
}

// 阈值变更时清空结果（避免阈值与结果不匹配）
const handleThresholdChange = () => {
  if (hasAnalysisResult.value) {
    hasAnalysisResult.value = false
    similarAccountList.value = []
  }
}

// 获取最高重叠率
const getMaxOverlapRate = () => {
  if (similarAccountList.value.length === 0) return 0
  return Math.max(...similarAccountList.value.map(item => item.overlapRate))
}

// 格式化分析时间
const formatAnalysisTime = () => {
  if (!analysisTime.value) return '——'
  const date = new Date(analysisTime.value)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 5. 其他辅助方法
// 返回上一页
const handleGoBack = () => {
  router.back()
}

// 查看账号详情
const handleViewAccountDetail = (id: number) => {
  router.push({
    path: '/member/internet-account/detail',
    query: { id }
  })
}
</script>

<style scoped lang="scss">
.internet-account-analysis-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;

  // 页面头部
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 16px;

    .header-actions {
      display: flex;
      gap: 16px;
      align-items: center;
      flex-wrap: wrap;

      .threshold-form {
        display: flex;
        align-items: center;
        gap: 12px;
        flex-wrap: wrap;
      }
    }
  }

  // 内容容器
  .content-container {
    margin-bottom: 20px;
  }

  // 账号列表卡片
  .account-list-card {
    height: 100%;
    min-height: 600px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      flex-wrap: wrap;
      gap: 12px;

      .search-input {
        width: 280px;
        min-width: 200px;
      }
    }

    .username-tag {
      color: #1890ff;
      font-weight: 500;
    }

    .fan-count {
      font-family: monospace;
    }

    .account-pagination {
      margin-top: 16px;
      text-align: right;
    }
  }

  // 分析结果卡片
  .analysis-result-card {
    height: 100%;
    min-height: 600px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      flex-wrap: wrap;
      gap: 12px;

      .status-tag-group {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        align-items: center;

        .target-account-tag {
          background-color: #e6f7ff;
          color: #1890ff;
          border-color: #91d5ff;
        }
      }
    }

    .empty-result {
      height: 500px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 20px;

      .lower-threshold-btn {
        color: #1890ff;
        text-decoration: underline;
      }
    }

    .loading-result {
      height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .result-content {
      .analysis-statistics {
        margin-bottom: 20px;
        padding: 10px;
        background-color: #f9f9f9;
        border-radius: 4px;
      }

      .table-container {
        .similar-table {
          margin-top: 16px;
        }

        .overlap-rate-container {
          display: flex;
          align-items: center;
          gap: 8px;
          justify-content: center;
        }

        .rate-text {
          font-size: 12px;
          color: #666;
          min-width: 40px;
          text-align: right;
        }

        .common-fan-count {
          color: #27ae60;
          font-weight: 500;
        }
      }
    }
  }

  // 响应式调整
  @media (max-width: 1200px) {
    .content-container {
      .el-col {
        &:nth-child(1), &:nth-child(2) {
          flex: 0 0 100%;
          width: 100% !important;
        }
      }
    }

    .account-list-card, .analysis-result-card {
      min-height: auto;
      margin-bottom: 20px;
    }
  }
}
</style>
